/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.bsly.modules.sys.interceptor;


import io.bsly.common.exception.RRException;
import io.bsly.common.utils.Constant;
import io.bsly.common.utils.JwtUtils;
import io.bsly.modules.app.annotation.JwtIgnore;
import io.bsly.modules.app.entity.localEntity.UserEntity;
import io.bsly.modules.app.service.localmaster.UserService;
import io.bsly.modules.sys.entity.SysUserEntity;
import io.bsly.modules.sys.service.SysUserService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 */
@Component
public class SysTokenInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    SysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)   {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);
        if (jwtIgnore != null) {
            return true;
        }

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        //获取用户凭证header  token
        String token = request.getHeader(jwtUtils.getHeader());
        if(StringUtils.isBlank(token)){
            token = request.getParameter(jwtUtils.getHeader());
        }

        //凭证为空
        if(StringUtils.isBlank(token)){
            throw new RRException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
            throw new RRException(jwtUtils.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }

        SysUserEntity userEntity = sysUserService.getById(Long.parseLong(claims.getSubject()));
        if (userEntity.getStatus()==0){
            throw new RRException("用户已冻结");
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(Constant.USER_KEY, Long.parseLong(claims.getSubject()));

        return true;
    }
}
